<?php

namespace app\store\service;

use app\store\model\GroupGoods;
use think\db\exception\DbException;
use think\facade\Db;

class GroupGoodsService
{
    /**
     * 获取拼团商品列表
     * */
    public  function getGroupGoodsList($param)
    {   
        $store_id = session('store_id');

        $query = GroupGoods::withOutField('goods_attr,delete_time')
                       ->where('store_id',$store_id);



        if(isset($param['status']) && $param['status'] != ''){
            $query->where('status',$param['status']);
        }

        if(!empty($param['keyword'])){
            $query->where('goods_name',$param['keyword']);
        }


        $groupGoods = $query->order('id','desc')->paginate(['list_rows' => 10]);
                            
                                            
        return $groupGoods;
    }


    /**
     * 获取拼团商品列表
     * */
    public function getGroupGoodsOptions($param)
    {
        $store_id = session('store_id');

        $query = Db::name('group_goods')
                   ->field('id,goods_name,main_image,market_price,sell_price,group_price,stock,create_time')
                   ->where(['store_id' => $store_id,'status' => 1])
                   ->order('id','desc') ;

        if(isset($param['status']) && $param['status'] != ''){
            $query->where('status',$param['status']);
        }

        if(!empty($param['keyword'])){
            $query->where('goods_name',$param['keyword']);
        }

        if (!empty($param['group_activity_id'])){
            $goodIds = Db::name('group_activity_goods')
                             ->field('group_goods_id')
                             ->where('group_activity_id',$param['group_activity_id'])->select();
            if (!$goodIds->isEmpty()){
                $ids = array_column($goodIds->toArray(),'group_goods_id');
                $query->whereNotIn('id',$ids);
            }

        }


        $groupGoods = $query->paginate(['list_rows' => 10]);


        return $groupGoods;
    }


    /**
     * 根据活动查看商品
     * */
    public function getActivityGoodsList($group_activity_id,$keyword)
    {

        $store_id = session('store_id');
        $query = Db::name('group_goods')
                  ->alias('a')
                  ->field('a.id,a.goods_name,a.main_image,a.sell_price,a.group_price,a.create_time,a.stock,b.id as mid_id')
                  ->join('group_activity_goods b','a.id=b.group_goods_id')
                  ->where(['a.store_id' => $store_id,'b.group_activity_id' => $group_activity_id])
                  ->order('a.id','desc');

       if (!empty($keyword)){
           $query->whereLike('a.goods_name',"%$keyword%");
       }

       $goods = $query->paginate(['list_rows' => 10, 'query' => ['group_activity_id' => $group_activity_id]]);

       return $goods;
    }


    /**
     * 查询单个拼团商品
     * */
    public function findGroupGoods($id)
    {
        $model = new GroupGoods();
        $groupGoods = $model->withOutField('create_time,update_time,delete_time')
                        ->with(['goodsContent','items'])
                        ->find($id);

        return $groupGoods;
    }


    /**
     * 保存拼团商品
     * */
    public function saveGroupGoods($data)
    {
        $data['store_id'] = session('store_id');
        $skus = [];
        $this->formatGoodsInfo($data,$skus);
        try {

            $groupGoods = GroupGoods::create($data);
            if ($data['spec_type'] == 2){
                $groupGoods->items()->saveAll($skus);
            }
            $groupGoods->goodsContent()->save(['content' => $data['content']]);
            return $groupGoods['id'];
        }catch (DbException $e){
            return false;
        }

    }

    /**
     * 更新拼团商品
     * */
    public function updateGroupGoods($data)
    {

        $skus = [];
        $this->formatGoodsInfo($data,$skus);
        $groupGoods = GroupGoods::update($data);
        if ($data['spec_type'] == 2){
            $groupGoods->items()->saveAll($skus);
        }

        $groupGoods->goodsContent()->where('group_goods_id',$data['id'])->update(['content' => $data['content']]);


        return $groupGoods['id'];
    }

    /**
     * 格式化商品信息
     * */
    protected function formatGoodsInfo(&$data,&$skus)
    {
        if ($data['spec_type']==2 && !empty($data['skus'])){
            $skus = json_decode($data['skus'], true);
            $data['market_price'] = min(array_column($skus,'market_price'));
            $data['sell_price'] = min(array_column($skus,'sell_price'));
            $data['group_price'] = min(array_column($skus,'group_price'));
            $data['stock'] =  array_sum(array_column($skus,'stock'));
        }

    }

}